﻿using MyHelper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using clf.weighing.entity;

namespace weighing
{
    public class MaterialPriceDao : BaseDao<MaterialPrice>
    {
        #region instance

        private static MaterialPriceDao? instance;
        public static MaterialPriceDao Instance => instance ??= new MaterialPriceDao();

        public override string GetTableName()
        {
            return TableName.material_price.ToString();
        }
        #endregion

        public MaterialPrice? GetMaterialCurrPrice(long materialId, MaterialPriceType type)
        {
            if (materialId <= 0) return null;            
            string now = "'" + DateTimeHelper.getCurrentDateTime() + "'";
            String condition = $@"{MaterialPriceField.material_id} = {materialId} and {MaterialPriceField.effective_time} <= {now} and {MaterialPriceField.failure_time} >={now} and {MaterialPriceField.type} = {(int)type} ";
            String sql = SqlBuilder.GetSelectSql(GetTableName(), null, condition, null, null, "add_time desc", 1, 0);
            var data = Sqlite.Select<MaterialPrice>(sql);
            return data.FirstOrDefault();
        }

        public List<MaterialPrice> SelectPricesByMaterialId(long materialId, MaterialPriceType type)
        {
            String condition = $@"{MaterialPriceField.material_id} = {materialId} and {MaterialPriceField.type}={(int)type}";
            String sql = SqlBuilder.GetSelectSqlWithSoftDeleteCondition(GetTableName(), null, condition, null, null, $"{MaterialPriceField.effective_time} desc");
            return Sqlite.Select<MaterialPrice>(sql);
        }

        public int UpdatePrice(MaterialPrice oldPrice, MaterialPrice newPrice)
        {
            string updateSql = SqlBuilder.GetUpdateSql(oldPrice);
            string insertSql = SqlBuilder.GetInsertSql(newPrice);
            string[] sqls = new string[] { updateSql, insertSql };
            return Sqlite.TransactionExecute(sqls);
        }

        public MaterialPrice? FindByMId(long materialId)
        {
            String condition = $"{MaterialPriceField.material_id} = {materialId} ";
            string order = $"{MaterialPriceField.effective_time} desc";
            String sql = SqlBuilder.GetSelectSqlWithSoftDeleteCondition(GetTableName(), null, condition, null, null, order);
            return Sqlite.Select<MaterialPrice>(sql).FirstOrDefault();
        }
    }
}
